﻿// COPYRIGHT 2012, Justin Michalczak
//
// This file is licenced to the public under the Apache
// License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License.
// You may obtain a copy of the License at:
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

using System;
using System.Collections.Generic;
using System.Linq;

using CopperVineSoftware.Stackr.Parser;
using CopperVineSoftware.Stackr.Parser.Lexemes;

namespace CopperVineSoftware.Stackr.Compiler.DCPU16Assembly
{
    /// <summary>Compiles programs into DCPU-16 assembly.</summary>
    sealed class ProgramCompiler
    {
        /// <summary>Compiles a program.</summary>
        /// <param name="program">Program to compile.</param>
        /// <returns>The compiled program instructions.</returns>
        /// <exception cref="ArgumentNullException">If <paramref name="program"/> is <c>null</c>.</exception>
        public static IEnumerable<string> Compile(Program program)
        {
            if (program == null)
                throw new ArgumentNullException("program");

            IEnumerable<BuiltInFunctionDefinition> builtInFunctions = BuiltInFunctionDefinition.GetBuiltInFunctions();
            StatementCompiler statementCompiler = new StatementCompiler(program.Definitions.Concat(builtInFunctions));
            DefinitionCompiler definitionCompiler = new DefinitionCompiler(statementCompiler);

            // Compile built-in functions, starting with reset.
            foreach (string instruction in definitionCompiler.Compile(builtInFunctions.Where((d) => d.Name == "reset")))
                yield return instruction;
            foreach (string instruction in definitionCompiler.Compile(builtInFunctions.Where((d) => d.Name != "reset")))
                yield return instruction;

            foreach (string instruction in definitionCompiler.Compile(program.Main))
                yield return instruction;

            // Compile program definitions.
            foreach (string instruction in definitionCompiler.Compile(program.Definitions))
                yield return instruction;
        }

        private ProgramCompiler()
        {
        }
    }
}
